const fs = require('fs');
const path = require('path');


function getFileContent(fileName,callback){

  const fullFileName = path.resolve(__dirname,'files',fileName);
  fs.readFile(fullFileName,(err, data) => {
    if (err) throw err;
    callback(
       JSON.parse(data.toString()) 
    )   
  });

}

//callback-hell 回调地狱 代码复杂 嵌套很不友好
getFileContent('a.json',adata=>{
  console.log('a---',adata)

  getFileContent('b.json',bdata=>{
    console.log('b---',bdata)

    getFileContent('c.json',cdata=>{
      console.log('c---',cdata)
    });

  });

});


//使用promise获取内容
function getFileContent2(fileName){

  const promise = new Promise((resolve,reject)=>{

    const fullFileName = path.resolve(__dirname,'files',fileName);
    fs.readFile(fullFileName,(err, data) => {
      if (err) throw err;
      resolve(
        JSON.parse(data.toString()) 
      )   
    });

  })

  return promise;
  
}

getFileContent2('a.json').then(adata=>{
  console.log('a======',adata)
  return getFileContent2(adata.next)
}).then(bdata=>{
  console.log('b======',bdata)
  return getFileContent2(bdata.next)
}).then(cdata=>{
  console.log('c======',cdata)
})
